# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 单一聚合first操作.py
# @Author: dongguangwen
# @Date  : 2025-06-14 19:12
from pymongo import MongoClient

# 连接到MongoDB（默认端口27017）
client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')

# 创建数据库和集合
db = client['learning_mongodb']
collection = db['users']


pipeline = [
    {"$sort": {"age": 1}},  # 年龄升序排列
    {
        "$group": {
            "_id": None,
            "youngest_user": {"$first": "$name"}
        }
    }
]
result = list(db.users.aggregate(pipeline))
print(result)
print("最年轻的用户:", result[0]["youngest_user"])

"""
[{'_id': None, 'youngest_user': 'User_2'}]
最年轻的用户: User_2
"""
